<?php
namespace PsiFramework\Classes\Util\Database\Filters;

use PsiFramework\Classes\Util\Database\Query\SqlColumn;

use PsiFramework\Classes\Util\Database\Query\SqlFunction;

use PsiFramework\Classes\Util\Database\Query\SqlTable;

use \PsiFramework\Classes\Util\Database\Query\SqlOrder;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The Paginator is used to paginate results from a database
 *
 * @package Util.Database.Filters
 */
class Paginator
{

    protected /*int*/        $_nbResults ;
    protected /*int*/        $_page ;
    protected /*SqlOrder[]*/ $_orders ;

    public function __construct(
        /*SqlOrder[]*/ $orders=array(),
        /*int*/ $nbResults=null,
        /*int*/ $page=null
    )
    {
        $this->_orders = $orders ;
        $this->_nbResults = $nbResults ;
        $this->_page = $page ;
    }

    public function getNbResults()
    {
        return $this->_nbResults ;
    }

    public function getPage()
    {
        return $this->_page ;
    }

    public function getOrders()
    {
        return $this->_orders ;
    }

    public function setNbResults(/*int*/ $nbResults)
    {
        $this->_nbResults = $nbResults;
    }

    public function setPage(/*int*/ $page)
    {
        $this->_page = $page;
    }

    public function setOrders(/*SqlOrder[]*/ $orders)
    {
        $this->_orders = $orders;
    }

    public function addOrder(SqlOrder $order, /*boolean*/ $forceReplace=true)
    {
        $table = null;
        $tableName = '';
        $column = $order->getColumn();
        if ($column instanceof SqlTable) {
            $table = $column->getTable();
        }
        if (!is_null($table)) {
            if (is_string($table)) {
                $tableName = $table;
            } else if ($table instanceof SqlTable) {
                $tableName = $table->getName();
            }
        }
        
        $key = '';
        if ($column instanceof SqlColumn) {
            if (!isNullOrEmptyString($tableName)) {
                $key .= $tableName.'-';
            }
            $key .= $column->getName();
        } else if ($column instanceof SqlFunction) {
            if (!isNullOrEmptyString($column->getAlias())) {
                $key = $column->getAlias();
            } else {
                //TODO revoir
                $key = $column->getName();
            }
        }
        
        if ($forceReplace || !array_key_exists($key, $this->_orders)) {
            $this->_orders[$key] = $order;
        }
    }
}
